package org.serverct.finalfight.game.hadesgame.events;

import org.bukkit.entity.Item;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;
import org.serverct.finalfight.FinalFight;
import org.serverct.finalfight.game.hadesgame.EventType;
import org.serverct.finalfight.internal.game.basic.BasicGame;
import org.serverct.finalfight.internal.game.hadesgame.ContinuousEvent;
import org.serverct.finalfight.internal.game.hadesgame.Factorable;

import java.util.HashSet;
import java.util.UUID;

public class MoreDrops extends ContinuousEvent implements Listener, Factorable {

    public MoreDrops(BasicGame game, EventType type) {
        super(game, type);
        this.setFactor((int) (Math.random() * 5));
    }

    @EventHandler
    public void onBlockDropExp(BlockBreakEvent event) {
        event.setExpToDrop((int) (event.getExpToDrop() * this.factor));
    }

    @EventHandler
    public void onEntityDropExp(EntityDeathEvent event) {
        event.setDroppedExp((int) (event.getDroppedExp() * this.factor));
    }

    public static HashSet<UUID> fromPlayer = new HashSet<>();

    @EventHandler
    public void onDrop(ItemSpawnEvent event) {
        Item drop = event.getEntity();
        if (fromPlayer.contains(drop.getUniqueId())) {
            return;
        }
        if (this.game.worldManager.world == drop.getWorld() ||
                this.game.worldManager.nether == drop.getWorld() ||
                this.game.worldManager.end == drop.getWorld()) {
            ItemStack item = drop.getItemStack();
            item.setAmount((int) (item.getAmount() * this.factor));
            drop.setItemStack(item);
        }
    }

    @EventHandler
    public void onBlockDrop(PlayerDropItemEvent event) {
        fromPlayer.add(event.getItemDrop().getUniqueId());
        new BukkitRunnable() {
            @Override
            public void run() {
                fromPlayer.remove(event.getItemDrop().getUniqueId());
            }
        }.runTaskLaterAsynchronously(FinalFight.plugin, 1L);
    }

    @Override
    public void setFactor(double factor) {
        this.factor = factor;
    }

    @Override
    public double getFactor() {
        return this.factor;
    }
}
